package com.cf.serialize;

import com.cf.common.util.mapping.BeanMapper;
import com.cf.common.util.mapping.DefaultBeanMapper;
import com.cf.game.service.util.BeanFactoryUtil;
import com.cf.game.service.util.ObjectJsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * game-server-MessageSerializeService
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/4/28 下午 05:24
 */

public class MessageConvertService {

    private Map<Integer, Class> messageType = new HashMap<>();

    public void registorMessageConvert(Integer type, Class messageTypeClass) {
        messageType.put(type, messageTypeClass);
    }

    public Request serialize(String message) throws IOException {
        MessageWrapper messageMap = ObjectJsonUtil.toObject(message, MessageWrapper.class);
        if (messageMap != null) {
            Class targetMessageType = messageType.get(messageMap.getMessageType());
            if (targetMessageType != null) {
                Object map = BeanFactoryUtil.getBean(BeanMapper.class).map(messageMap.getRequest(), targetMessageType);
                if (map instanceof Request)
                    return (Request) map;
            }
        }
        return null;
    }
}
